# coding=utf-8
import os
import Metashape
import json

## Initialize Project
print("Open Data File to Create Project...")
file = open('mnt/sdb1/home/hzy/projects/data.json','r',encoding='utf-8')

text = file.read()

if text.startswith(u'\ufeff'):
    text = text.encode('utf-8')[3:].decode('utf-8')

jsonObject = json.loads(text)
jsonChunks = jsonObject['Chunks']

doc = Metashape.app.document

dataFolder = "/mnt/sdb1/home/hzy/data"

for i in range(0,len(jsonChunks)):
    # Add Chunk and Set Label
    chunk = doc.addChunk()
    chunk.label = jsonChunks[i]['Chunk']
    groups = jsonChunks[i]['Groups']

    images = []

    for group in groups:
        startIndex = int(group['StartIndex'])
        endIndex = int(group['EndIndex'])
        folder= group['Folder']
        
        for index in range(startIndex,endIndex):

            #imageFile = "/".join(dataFolder,"%s/DJI_%04d.jpg"%(folder,index))
            fileName = "DJI_%04d.JPG"%(index)
            imageFile=os.path.join(dataFolder, folder,  fileName)
            print(imageFile)
            images.append(imageFile)

    chunk.addPhotos(images,layout=Metashape.UndefinedLayout)

doc.save(jsonObject['File'])

